import WeCropper from '../../component/cropper/we-cropper.js';
const app = getApp();
const { qyWXCheckSeesion } = require('../../utils/ws/ws-wxwork');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isWXWork: app.isWXWork,
    posterDetail: null,
    posterData: [],
    posterBg: null,
    linkPages: [],
    containerHeight: 0,
    previewHeight: 0,
    previewWidth: 0,
    scale: 1,
    defaultQrcode: `${app.siteInfo.domain}addons/ws_multishop/plugin/poster/static/images/qrcode.png`,
    submitting: false,
    sheetType: 'template',
    templateList: [],
    page: 1,
    hasMore: true,
    openSetting: false,
    colorList: [
      '#000000', '#434343', '#666666', '#999999', '#b7b7b7', '#cccccc', '#d9d9d9', '#efefef', '#f3f3f3', '#ffffff',
      '#980000', '#ff0000', '#ff9900', '#ffff00', '#00ff00', '#00ffff', '#4a86e8', '#0000ff', '#9900ff', '#ff00ff',
      '#e6b8af', '#f4cccc', '#fce5cd', '#fff2cc', '#d9ead3', '#d0e0e3', '#c9daf8', '#cfe2f3', '#d9d2e9', '#ead1dc',
      '#dd7e6b', '#ea9999', '#f9cb9c', '#ffe599', '#b6d7a8', '#a2c4c9', '#a4c2f4', '#9fc5e8', '#b4a7d6', '#d5a6bd',
      '#cc4125', '#e06666', '#f6b26b', '#ffd966', '#93c47d', '#76a5af', '#6d9eeb', '#6fa8dc', '#8e7cc3', '#c27ba0',
      '#a61c00', '#cc0000', '#e69138', '#f1c232', '#6aa84f', '#45818e', '#3c78d8', '#3d85c6', '#674ea7', '#a64d79',
      '#85200c', '#990000', '#b45f06', '#bf9000', '#38761d', '#134f5c', '#1155cc', '#0b5394', '#351c75', '#741b47',
      '#5b0f00', '#660000', '#783f04', '#7f6000', '#274e13', '#0c343d', '#1c4587', '#073763', '#20124d', '#4c1130',
    ],
    fontList: [
      {
        name: '平方字体',
        path: 'pingfang.ttf',
      },
      {
        name: '濑户字体',
        path: 'SetoFont.TTF',
      },
      {
        name: '思源黑体',
        path: 'SourceHanSansSC-Bold.otf',
      },
      {
        name: '思源柔黑',
        path: 'SourceHanSerifSC-Regular.otf',
      },
      {
        name: '思源宋体',
        path: 'SourceHanSerifSC-Bold.otf',
      },
      {
        name: '手书体',
        path: '手书体.ttf',
      },
      {
        name: '新蒂小丸子字体',
        path: '新蒂小丸子字体.ttf',
      },
    ],
    showCropper: false,
    cropperOpt: {},
    uploadingImage: false,
    jumpName: '', // 二维码跳转路径名字
    currentTab: 0, // 修改文字切换
    keyboardHeight: 0, // 键盘高度
    selectedItem: {}, // 文字信息
    focusItem: false, // 是否获取焦点
  },
  usedFonts: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({ title: '制作海报' });
    const { type, tmpid } = this.options || {};
    const device = wx.getSystemInfoSync();
    this.windowWidth = device.windowWidth;
    this.windowHeight = device.windowHeight;
    const ROW_SIZE = 6;
    const colorRows = [];
    for (let index = 0; index < this.data.colorList.length; index += ROW_SIZE) {
      colorRows.push(this.data.colorList.slice(index, index + ROW_SIZE));
    }
    const lastRow = colorRows[colorRows.length - 1];
    if (lastRow.length < ROW_SIZE) {
      lastRow.push(...new Array(ROW_SIZE - lastRow.length).fill('none'));
    }
    this.setData(
      {
        shopid: (app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.shopid) || '',
        openid: wx.getStorageSync('OPENID') || wx.getStorageSync('openid'),
        type,
        tmpid,
        cropperOpt: {
          id: 'cropper',
          pixelRatio: device.pixelRatio,
          width: this.windowWidth,
          height: this.windowHeight - (this.windowWidth / 750) * 100,
          scale: 2.5,
          zoom: 8,
        },
        posterDetail: wx.getStorageSync('posterDetail'),
        colorRows,
      },
      () => {
        this.setPreviewSize();
        this.switchTemplate();
        this.cropper = new WeCropper({
          ...this.data.cropperOpt,
        })
          .on('beforeImageLoad', (ctx) => {
            wx.showToast({
              title: '上传中',
              icon: 'loading',
              duration: 20000,
            });
          })
          .on('imageLoad', (ctx) => {
            wx.hideToast();
          })
          .updateCanvas();
      },
    );
  },
  clickTab: function (e) {
    let that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
      });
    }
  },
  bindTextFocus(e) {
    this.setData({
      keyboardHeight: e.detail.height || 0,
    });
  },
  bindTextBlur() {
    this.setData({
      keyboardHeight: 0,
    });
  },
  loadPosterData() {
    const { type, tmpid } = this.data || {};
    if (Number(type) === 4) {
      this.setData({
        posterType: 'card',
      });
    } else {
      this.setData({
        posterType: '',
      });
    }
    app.util.request({
      url: 'wxapp/poster/getPages',
      data: {
        id: tmpid,
        corpid: wx.getStorageSync('qyUserInfo').corpid,
      },
      method: 'POST',
      success: (res) => {
        if (res.data.result) {
          this.setData({
            posterData: (res.data.result.data || []).map((v, index) => {
              const data = Object.assign({}, v, {
                scaledLeft: this.scaledPixel(v.left),
                scaledTop: this.scaledPixel(v.top),
                scaledWidth: this.scaledPixel(v.width),
                scaledHeight: this.scaledPixel(v.height),
              });
              if (v.type === 'picture' || v.type === 'qr') {
                if (v.picture) {
                  data.picture = (v.picture.startsWith('http') ? '' : app.siteInfo.attachment_url) + v.picture;
                }
                data.btnPosition = (data.scaledTop + data.scaledHeight + this.scaledPixel('90')) > this.data.previewHeight ? 'top' : 'bottom';
              }
              if (v.size) {
                data.sizeValue = parseFloat(v.size.endsWith('px') ? v.size.slice(0, -2) : v.size);
                data.scaledSize = this.scaledPixel(v.size);
              }
              if (v.namefont) {
                data.fontName = (this.data.fontList.find(font => font.path === v.namefont) || {}).name;
              }
              if (v.color && v.color.startsWith('#') && v.color.length === 4) {
                data.color = `#${v.color[1]}${v.color[1]}${v.color[2]}${v.color[2]}${v.color[3]}${v.color[3]}`;
              }
              data.style = this.generateStyle(data, index);
              return data;
            }),
            posterBg: (res.data.result.bg.startsWith('http') ? '' : app.siteInfo.attachment_url) + res.data.result.bg,
            linkPages: res.data.result.pages ? res.data.result.pages.map((item, index) => {
              const data = Object.assign({}, item, {
                checked: false,
                title: item.title,
                wxapp_url: item.wxapp_url,
              });
              if (index === 0) {
                data.checked = true;
              }
              return data;
            }) : [],
            jumpName: res.data.result.pages && res.data.result.pages[0].title,
          });
          // this.loadFonts();
        }
      },
    });
  },
  setPreviewSize() {
    const bottomHeight = 418 * (this.windowWidth / 750);
    const containerHeight = this.windowHeight - bottomHeight;
    const containerWidth = this.windowWidth;
    let previewHeight = containerHeight - 40;
    let previewWidth = containerWidth - 40;
    let scale = 1;
    const isLong = this.data.posterDetail.is_long === '1';
    const ratio = 568 / 320;
    if (!isLong) {
      if (previewWidth * ratio < previewHeight) {
        previewHeight = previewWidth * ratio;
      } else {
        previewWidth = previewHeight / ratio;
      }
      scale = previewWidth / 320;
    } else {
      const actualHeight = parseFloat(this.data.posterDetail.long_height);
      const actualWidth = parseFloat(this.data.posterDetail.long_width);
      previewHeight = previewWidth * (actualHeight / actualWidth);
      scale = previewWidth / actualWidth;
    }
    this.setData({ containerHeight, previewHeight, previewWidth, scale: scale }, () => {
      this.loadPosterData();
    });

  },
  loadFonts() {
    // Object.values(this.usedFonts).forEach(font => {
    this.data.fontList.forEach((font) => {
      wx.loadFontFace({
        family: font.name,
        source: `url("${app.siteInfo.domain}app/resource/fonts/${font.path}")`,
        success: (res) => console.log('load font ', font.name, res),
        fail: (err) => console.error('load font fail ', font.name, err),
      });
    });
  },
  scaledPixel(pixel) {
    const pixelValue = parseFloat(`${pixel}`.endsWith('px') ? pixel.slice(0, -2) : pixel);
    return this.data.scale * pixelValue;
  },
  generateStyle(data, index) {
    let style = `
      position: absolute;
      z-index: ${10 + index};
      left: ${data.scaledLeft}px;
      top: ${data.scaledTop}px;
      width: ${data.scaledWidth}px;
      height: ${data.scaledHeight}px;
    `;
    if (data.scaledSize) {
      style += `
        font-size: ${data.scaledSize}px;
        color: ${data.color};
        text-align: ${data.namealign || data.align};
        line-height: 1;
        word-break: break-all;
      `;
    }
    if (data.namefont) {
      const font = this.data.fontList.find((item) => item.path === data.namefont);
      if (!this.usedFonts[font.name]) {
        this.usedFonts[font.name] = font;
      }
      style += `font-family: ${font ? font.name : ''};`;
    }
    return style;
  },
  closeSheet() {
    this.setData({
      sheetType: 'template',
    });
  },
  closeEdit() {
    if (this.data.sheetType === 'qr') {
      this.setData({
        linkPages: this.data.linkPages.map((item, index) => {
          const data = Object.assign({}, item, {
            checked: false,
            title: item.title,
            wxapp_url: item.wxapp_url,
          });
          if (data.title === this.data.jumpName) {
            data.checked = true;
          }
          return data;
        }),
      });
    }
    this.setData({
      selectedIndex: -1,
      currentTab: 0,
    });
    this.closeSheet();
  },
  switchTemplate() {
    this.setData({
      sheetType: 'template',
      templateList: [this.data.posterDetail],
      page: 1,
      hasMore: true,
    });
    this.loadTemplates();
  },
  loadTemplates() {
    const { categoryid, categorysubid } = this.data.posterDetail;
    if (!this.data.hasMore) {
      return;
    }
    app.util.request({
      url: 'wxapp/poster/getPosterLists',
      data: {
        page: this.data.page,
        psize: 10,
        categoryid: categoryid,
        categorysubid: categorysubid || '',
        openid: this.data.openid,
        corpid: wx.getStorageSync('qyUserInfo').corpid,
      },
      method: 'POST',
      success: (res) => {
        if (res.statusCode === 200) {
          let list = res.data.result || [];
          this.setData({
            templateList: this.data.templateList.concat(list.filter((v) => v.id !== this.data.posterDetail.id)),
            page: this.data.page + 1,
            hasMore: list.length > 0,
          });
        }
      },
    });
  },
  selectTemplate(e) {
    const index = parseFloat(e.currentTarget.dataset.index);
    const template = this.data.templateList[index];
    if (template) {
      this.setData(
        {
          type: template.type,
          tmpid: template.id,
          posterDetail: template,
        },
        () => this.setPreviewSize(),
      );
    }
    this.setData({
      selectedIndex: -1,
      currentTab: 0,
    });
    this.closeSheet();
  },
  selectItem(e) {
    const posterType = this.data.type;
    const type = e.currentTarget.dataset.type;
    const index = parseFloat(e.currentTarget.dataset.index);
    const item = this.data.posterData[index];

    if (posterType === '3') {
      return;
    }

    if (item) {
      this.setData({
        sheetType: type || this.data.sheetType,
        selectedIndex: index,
        selectedItem: item,
        focusItem: true,
      });
    }
  },
  changeTextSize(e) {
    const value = e.detail.value;
    const data = this.data.posterData[this.data.selectedIndex];
    data.sizeValue = value;
    data.size = `${value}px`;
    data.scaledSize = this.scaledPixel(value);
    data.style = this.generateStyle(data, this.data.selectedIndex);
    this.setData({ [`posterData[${this.data.selectedIndex}]`]: data });
  },
  changeAlign(e) {
    const value = e.detail.value;
    const data = this.data.posterData[this.data.selectedIndex];
    data.namealign = value;
    data.style = this.generateStyle(data, this.data.selectedIndex);
    this.setData({ [`posterData[${this.data.selectedIndex}]`]: data });
  },
  changeTextValue(e) {
    const value = e.detail.value;
    const data = this.data.posterData[this.data.selectedIndex];
    data.namecontent = value;
    this.setData({ [`posterData[${this.data.selectedIndex}]`]: data });
  },
  changeTextFont(e) {
    const font = e.currentTarget.dataset.font;
    const fontName = e.currentTarget.dataset.name;
    const data = this.data.posterData[this.data.selectedIndex];
    data.namefont = font;
    data.fontName = fontName;
    data.style = this.generateStyle(data, this.data.selectedIndex);
    this.setData({ [`posterData[${this.data.selectedIndex}]`]: data });
  },
  changeTextColor(e) {
    const color = e.currentTarget.dataset.color;
    const data = this.data.posterData[this.data.selectedIndex];
    data.color = color;
    data.style = this.generateStyle(data, this.data.selectedIndex);
    this.setData({ [`posterData[${this.data.selectedIndex}]`]: data });
  },
  showQrcodeSelector() {
    const itemList = (this.data.linkPages || []).map(page => {
      return `二维码跳转路径: ${page.title}`;
    });
    itemList.push('自定义二维码图片');
    if (this.data.isWXWork) {
      itemList.push('企业微信个人二维码');
    }
    wx.showActionSheet({
      itemList,
      success: ({ tapIndex }) => {
        if (tapIndex < this.data.linkPages.length) {
          this.pickPageLink(tapIndex);
        } else if (itemList[tapIndex] === '自定义二维码图片') {
          this.chooseImage();
        } else if (itemList[tapIndex] === '企业微信个人二维码') {
          this.getWXWorkQrcode();
        }
      },
      fail: (res) => {
        console.log(res.errMsg);
      },
    });
  },
  pickPageLink(index) {
    let pages = this.data.linkPages;
    let title = '';
    for (let i = 0; i < pages.length; i++) {
      const page = pages[i];
      if (i === index) {
        page.checked = true;
        title = page.title;
      } else {
        page.checked = false;
      }
    }
    this.setData({
      linkPages: pages,
      jumpName: title,
      selectedIndex: -1,
      [`posterData[${this.data.selectedIndex}].picture`]: null,
    });
    this.closeSheet();
  },
  getWXWorkQrcode() {
    qyWXCheckSeesion({
      success: () => {
        wx.qy.getQrCode({
          success: (res) => {
            const qrCode = res.qrCode;
            console.log('个人二维码', qrCode);
            this.setData({
              [`posterData[${this.data.selectedIndex}].picture`]: qrCode,
              jumpName: '个人二维码',
              linkPages: this.data.linkPages.map((item, index) => {
                const data = Object.assign({}, item, {
                  checked: false,
                  title: item.title,
                  wxapp_url: item.wxapp_url,
                });
                return data;
              }),
              selectedIndex: -1,
            });
            this.closeSheet();
          },
          fail: (res) => {
            console.log('企业微信个人二维码获取失败', res);
          },
        });
      },
      fail: () => {
        console.log('企业微信登录失败');
      },
    });
  },
  chooseImage() {
    const data = this.data.posterData[this.data.selectedIndex];
    const cutWidth = this.windowWidth - 150;
    const cutHeight = cutWidth * (data.scaledHeight / data.scaledWidth);
    this.cropper.cut = {
      x: 75,
      y: (this.data.cropperOpt.height - cutHeight) / 2,
      width: cutWidth,
      height: cutHeight,
    };
    this.cropper.cutt();
    this.cropper.methods();
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        let filePath = res.tempFilePaths[0];
        this.setData({
          showCropper: true,
        });
        this.cropper.pushOrign(filePath);
      },
    });
  },
  touchStart(e) {
    this.cropper.touchStart(e);
  },
  touchMove(e) {
    this.cropper.touchMove(e);
  },
  touchEnd(e) {
    this.cropper.touchEnd(e);
  },
  closeCropper() {
    this.setData({ showCropper: false });
  },
  getCropperImage() {
    const data = this.data.posterData[this.data.selectedIndex];
    this.setData({ uploadingImage: true });
    this.cropper.getCropperImage((src) => {
      if (src) {
        wx.uploadFile({
          url: app.util.url('utility/file/upload', { type: 'image', thumb: '0' }),
          filePath: src,
          name: 'file',
          success: (res) => {
            let resData = JSON.parse(res.data);
            if (res.statusCode === 200 && !resData.error && resData.url) {
              data.picture = resData.url;
              this.setData({
                uploadingImage: false,
                showCropper: false,
                [`posterData[${this.data.selectedIndex}]`]: data,
                jumpName: '自定义图片',
                linkPages: this.data.linkPages.map((item, index) => {
                  const data = Object.assign({}, item, {
                    checked: false,
                    title: item.title,
                    wxapp_url: item.wxapp_url,
                  });
                  return data;
                }),
                selectedIndex: -1,
              });
              this.closeSheet();
            } else {
              this.setData({ uploadingImage: false });
              wx.showToast({
                title: resData.error.message,
                icon: 'none',
              });
            }
          },
        });
      } else {
        wx.showToast({
          title: '获取图片地址失败，请重试',
          icon: 'none',
        });
      }
    });
  },
  createPicture() {
    // 连锁店用户门店id  add by wangjuan 2018/10/30
    let merchid = '';
    if (app.modules === 'ws_retailshop_bz' || app.modules === 'ws_retailshop_rz') {
      merchid = wx.getStorageSync('usermerchid');
    } else if (app.modules === 'ws_chainstore_ex') {
      merchid = wx.getStorageSync('merchid');
    }

    let pageUrl = '';
    let pages = this.data.linkPages;
    if (pages.length > 0) {
      for (let i in pages) {
        if (pages[i].checked) {
          pageUrl = pages[i].wxapp_url;
          break;
        }
      }
    }

    app.util.request({
      url: 'wxapp/poster/createPoster',
      data: {
        id: this.data.tmpid,
        data: JSON.stringify(
          (this.data.posterData || []).map((v) => ({
            left: v.left,
            top: v.top,
            type: v.type,
            width: v.width,
            height: v.height,
            size: v.size,
            color: v.color,
            namealign: v.namealign,
            namefont: v.namefont,
            namecontent: v.namecontent,
            picture: v.picture,
            corpid: wx.getStorageSync('qyUserInfo').corpid,
          })),
        ),
        page: pageUrl,
        openid: this.data.openid,
        merchid: merchid, // 连锁店用户门店id  add by wangjuan 2018/10/30
        shop_id: this.data.shopid, // 商城多商户兼容 lili 2019-1-24
      },
      method: 'POST',
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.status === 1) {
            this.setData({
              poster: res.data.result.url,
            });
          } else if (res.data.status === -1) {
            wx.showModal({
              title: '提示',
              content: res.data.result ? res.data.result.message : '暂无名片',
              success: (resp) => {
                if (resp.confirm) {
                  app.util.navigateTo('/common/component/universal-card/pages/card-edit', {}, true);
                } else if (res.cancel) {
                  this.setData({
                    showResult: false,
                    poster: '',
                  });
                }
              },
            });
          } else if (res.data.status === -2) {
            wx.showToast({
              title: res.data.result ? res.data.result.message : '海报生成失败',
              icon: 'none',
              duration: 2000,
            });
          }
        }
      },
    });
    this.closeSheet();
    this.setData({
      showResult: true,
    });
  },
  posterClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
  savePicture() {
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success: (res) => {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          this.downloadPoster();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          this.setData({
            openSetting: true,
          });
        } else {
          this.downloadPoster();
        }
      },
    });
  },
  downloadPoster() {
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: this.data.poster,
      success: (e) => {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: () => {
            wx.showModal({
              title: '提示',
              content: '图片保存成功',
              showCancel: false,
            });
          },
          fail: (e) => {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: (e) => {
            wx.hideLoading();
          },
        });
      },
      fail: (e) => {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + this.data.poster,
          showCancel: false,
        });
      },
      complete: (e) => {
        wx.hideLoading();
      },
    });
  },
  closePoster() {
    this.setData({
      showResult: false,
      poster: '',
    });
  },
});
